package com.zhiqingchun.web.login;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zhiqingchun.common.exception.AccountNotAvailableException;
import com.zhiqingchun.common.exception.InfoNotCompleteException;
import com.zhiqingchun.dao.account.IUserDao;
import com.zhiqingchun.dao.account.UserResult;
import com.zhiqingchun.pojo.Usr;

@Controller
@RequestMapping("/login.html")
public class LoginController {

	@RequestMapping(method = RequestMethod.GET)
	public String toLogin(ModelMap modelMap,HttpServletRequest request, HttpServletResponse response) {
		return "login/login";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String toLogin(ModelMap modelMap,HttpServletRequest request, HttpServletResponse response,
			String email, String pwd) {
		Usr usr = new Usr();
		if (StringUtils.isBlank(email) || StringUtils.isBlank(pwd))
			throw new InfoNotCompleteException("帐号和密码都必须填写");
		usr.setEmail(email);
		usr.setPwd(pwd);
		UserResult userResult = userDao.login(usr);
		if (userResult.isSuccess()) {
			HttpSession session = request.getSession();
			session.setMaxInactiveInterval(60*60); //一小时内有效
			session.setAttribute("user", userResult.getUsr());
		} else {
			throw new AccountNotAvailableException("登录帐号或者密码错误");
		}
		return "redirect:default.html";
	}

	@Autowired
	private IUserDao userDao;

	public IUserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}
}
